#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>

#include <linux/of.h>


#define BUFFER_SIZE (1024 * 4) // 4KB

static void *buf;
static dma_addr_t dma_handle;

static int my_probe(struct platform_device *pdev)
{
    struct device *dev = &pdev->dev;

    // 分配DMA缓冲区
    buf = kmalloc(BUFFER_SIZE, GFP_KERNEL);
    if (!buf) {
        printk(KERN_ERR "DMA buffer allocation failed\n");
        return -ENOMEM;
    }   

    // 将DMA缓冲区映射到物理地址
    dma_handle = dma_map_single(dev, buf, BUFFER_SIZE, DMA_TO_DEVICE);
    if (dma_mapping_error(NULL, dma_handle)) {
        printk(KERN_ERR "DMA buffer mapping failed\n");
        kfree(buf);
        return -ENOMEM;
    }   

    printk(KERN_INFO "DMA buffer allocated successfully\n");

    return 0;
}

static int my_remove(struct platform_device *pdev)
{
    struct device *dev = &pdev->dev;

    // 将DMA缓冲区从物理地址取消映射
    dma_unmap_single(dev, dma_handle, BUFFER_SIZE, DMA_TO_DEVICE);

    // 释放DMA缓冲区
    kfree(buf);

    printk(KERN_INFO "DMA buffer freed\n");

    return 0;
}

static const struct of_device_id my_of_match[] = {
    { .compatible = "my-dma-test", },
    {},
};
MODULE_DEVICE_TABLE(of, my_of_match);

static struct platform_driver my_driver = {
    .probe = my_probe,
    .remove = my_remove,
    .driver = {
        .name = "my-dma-test",
        .owner = THIS_MODULE,
        .of_match_table = of_match_ptr(my_of_match),
    },
};

module_platform_driver(my_driver);
MODULE_LICENSE("GPL");


